const app = getApp();
const _requsetCYZ = require('../../utils/requestData');
const _functionCYZ = require('../../utils/common.js');
var WxParse = require('../../wxParse/wxParse.js');
let goodsSpecArr = [];
const cart_storage_key = 'this_canting_shop_cart_data';
Page({
  data: {
    this_user_info:{},
    this_canting_setting:{},
    this_peisong_type:0,//0：店内 1：外卖
    this_fendian_id:0,
    this_table_id: 0,
    is_jiacai_action:0,
    this_fendian_info:{},
    this_shop_info: {},
    this_cate_list: [],
    this_goods_list: [],
    this_cate_data_id: 0,
    this_cate_data_name: '商品',
    this_cate_data_goods: null,
    guigeIsShow: false,
    this_spec_attr: [],
    this_spec_list: [],
    choose_spec_list: [],
    this_s_sku_id: '',
    this_s_shop_price: 0.00,
    this_s_market_price: 0.00,
    this_s_stock_num: 0,
    this_s_skuCoverImage: '',
    cart_list: [], //购物车信息
    this_goods_item_id: '', //当前下标
    isShowCartList: false,
    all_g_number: 0,
    all_g_price: '0.00',
    isSumbitLoading:false,

    this_data_share_title:'',
    this_data_share_img:'',
    isClickGoods:false
  },
  onPullDownRefresh: function () {
    var that = this;
    that.getIndexData();
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000);
  },
  onLoad: function (e) {
    let that = this;
    let _this = this,scene = app.getSceneData(e);
    // wx.setStorageSync(cart_storage_key, {})
    /**获取屏幕宽度 */
    wx.getSystemInfo({
      success: function (res) {
        var wp = res.windowWidth / 375;
        that.setData({
          pixelRatio: wp
        })
      },
    });
    //识别桌号
    let refereeId = 0;
    let table_id = 0;
    let fendian_id = 0;
    let peisong_type = 0;
    let is_jiacai_action = 0;
    refereeId = e.referee_id ? e.referee_id : (scene.uid ? scene.uid : 0);
    table_id = e.table_id ? e.table_id : (scene.table_id ? scene.table_id : 0);
    fendian_id = e.fendian_id ? e.fendian_id : (scene.fendian_id ? scene.fendian_id : 0);
    peisong_type = e.peisong_type ? e.peisong_type : (scene.peisong_type ? scene.peisong_type : 0);
    is_jiacai_action = e.is_jiacai_action || 0;
    //解析普通二维码打开小程序
    // if(table_id == ''){
    // 	if(qrcode_str.indexOf("table_id") != -1){
    // 		var vvvvvvval = qrcode_str.split('=');
    // 		if(vvvvvvval.length > 0 && vvvvvvval[1]){
    // 			table_id = vvvvvvval[1];
    // 		}
    // 	}
    // }
    _this.setData({
      this_table_id:table_id,
      this_fendian_id:fendian_id,
      this_peisong_type:peisong_type,
      is_jiacai_action:is_jiacai_action
    });
    if(peisong_type == 1){
      wx.setNavigationBarTitle({
        title: '外卖点餐',
      })
    }
    _this.getIndexData();
  },
  onShow:function(){
    this.getIndexData();
  },
  getIndexData: function () {
    let _this = this;
    _functionCYZ.CYZ_loading();
    var requestData = {};
    requestData.table_id = _this.data.this_table_id;
    requestData.fendian_id = _this.data.this_fendian_id;
    _requsetCYZ.cyz_requestPost('/CantingIndex/index', requestData, function (xyz_data) {
      wx.hideToast();
      if (xyz_data.code == 2) {
        app.getUserDataToken(function (token) {
          _this.getIndexData();
        });
        return false;
      }
      _this.setData({
        this_user_info:xyz_data.data.this_user_info,
        this_canting_setting:xyz_data.data.this_canting_setting,
        this_shop_info: xyz_data.data.this_shop_info,
        this_fendian_info:xyz_data.data.this_fendian_info,
        this_fendian_id:xyz_data.data.this_fendian_id,
        this_cate_list: xyz_data.data.this_cate_list,
        this_goods_list: xyz_data.data.this_cate_list
      });
      if (xyz_data.data.share_title != '') {
        _this.setData({
          this_data_share_title: xyz_data.data.share_title
        });
      }
      if (xyz_data.data.share_img != '') {
        _this.setData({
          this_data_share_img: xyz_data.data.share_img
        });
      }
      _this.syn_goods_number();

      // 获取购物车数据
      let cart_data = wx.getStorageSync(cart_storage_key) || {};
      _this.get_new_card_data(cart_data);
      if(xyz_data.data.is_table_order > 0 && _this.data.is_jiacai_action == 0){
        wx.navigateTo({
          url:"/pages/canting/order?table_id=" + _this.data.this_table_id + "&fendian_id=" + _this.data.this_fendian_id
        })
      }
    });
  },
  //同步购物车商品数量
  syn_goods_number: function () {
    let _this = this;
    let this_goods_list = _this.data.this_goods_list;
    let base_card_data = wx.getStorageSync(cart_storage_key) || {};
    let base_card_data_arr = Object.keys(base_card_data);
    let sdata = {};

    for (let i = 0; i < this_goods_list.length; i++) {
      let goods_list = this_goods_list[i].goods_list;
      if (goods_list != undefined) {
        for (var j = 0; j < goods_list.length; j++) {
          goods_list[j].cart_goods_number = 0;
          for (var bj = 0; bj < base_card_data_arr.length; bj++) {
            var cart_info = base_card_data[base_card_data_arr[bj]];
            if (cart_info.goods_id == goods_list[j].id) {
              goods_list[j].cart_goods_number += cart_info.cart_goods_number;
            }
          }
          sdata["this_goods_list[" + i + "].goods_list"] = goods_list;
          sdata["this_cate_list[" + i + "].goods_list"] = goods_list;
        }
      }
    }
    this.setData(sdata);
  },
  /**页面滚动 */
  onPageScroll: function (e) {
    var that = this;
    let top = that.data.top_height * that.data.pixelRatio;
    // 固定分类
    if (e.scrollTop > top && this.data.pageMenuFiexd == false) {
      this.setData({
        pageMenuFiexd: true
      })
    } else if (e.scrollTop < top && this.data.pageMenuFiexd == true) {
      this.setData({
        pageMenuFiexd: false
      })
    }
  },
  /**
   * 根据分类id，获取分类索引
   */
  get_cate_index: function (cate_id) {
    var that = this;
    var goods_cate = that.data.this_goods_list;
    for (var idx in goods_cate) {
      if (cate_id == goods_cate[idx]['id']) {
        return idx;
      }
    }
  },
  /**
   * 左侧菜品分类点击
   */
  bindLeftTap: function (event) {
    var that = this;
    var id = event.currentTarget.dataset.id; //通过event取到当前所点击的分类菜单的id
    var cate_c_id = event.currentTarget.dataset.cate_c_id || 0;
    var cname = event.currentTarget.dataset.cname;
    var cate_cname = event.currentTarget.dataset.cate_cname || '';
    var this_goods_list = that.data.this_goods_list;
    let s_type = 0;
    var cindex = that.get_cate_index(id);
    if (this_goods_list[cindex].goods_list != null) {
      this.setData({ //通过数据绑定，直接将ID塞到 scroll-into-view  对应的值里
        curListView: "list" + id, //右侧菜单scroll-into-view  对应的值
        classifySeleted: id, //左侧菜单scroll-into-view  对应的值
        this_cate_data_name: cname,
      })
    }
  },
  /**
   * 右侧商品滚动
   */
  onGoodsScroll: function (e) {
    var scrollHeight = e.detail.scrollTop //同样通过e获取右侧菜单，滚动到顶部，隐藏部分的高度
    var categorys = this.data.this_cate_list //这是一个数组，包含所有菜类和该分类下菜品
    if (categorys[0].id == 0) {
      return;
    }
    var sumHeight = 0; //自定一个一个变量，用来存每个菜类和菜品一共的高度
    for (var index in categorys) { //循环所有菜类和菜品
      var type = categorys[index]; //菜类
      if (type.goods_list == undefined) {
        return;
      }
      var dishSize = type.goods_list.length; //每个菜类下的所有菜品
      //用定义的变量 加等于 每个菜类标题的高度（15）+ 每个菜类下的所有菜品的数量（dishSize ）乘以 每个菜品的高度（100）
      //就是右侧菜单所有菜类标题和菜品的一共高度
      if (index == 0) {
        sumHeight += (dishSize * 95) * this.data.pixelRatio;
      } else {
        sumHeight += (33 + dishSize * 95) * this.data.pixelRatio;
      }
      if (scrollHeight <= sumHeight) { //判断当前滚动到顶部隐藏部分的高度，如果小于等于右侧菜单所有菜类和菜品的一共高度
        //那就把当前高度的 菜品属于所在类型的id传给左侧菜单的scroll-into-view 对应值里
        if (type.pid > 0) {
          this.setData({
            classifySeleted: type.pid,
            childSelected: type.id,
            views: 'cate' + type.pid,
            this_cate_data_name: type.name
          })
        } else {
          this.setData({
            classifySeleted: type.id,
            views: 'cate' + type.id,
            this_cate_data_name: type.name
          })
        }
        break; //跳出当前循环
      }
    }
  },
  //获取商品详情
  goods_info_bind: function (e) {
    let _this = this;
    let goods_id = e.currentTarget.id;
    let requestData = {};
    requestData.goods_id = goods_id;
    _requsetCYZ.cyz_requestPost('/CantingIndex/goodsInfo', requestData, function (xyz_data) {
      wx.hideToast();
      if (xyz_data.code == 2) {
        app.getUserDataToken(function (token) {
          _this.goods_info_bind(e);
        });
        return false;
      } else if (xyz_data.code == 1) {
        _this.setData({
          this_goods_show_info: xyz_data.data.goods_info,
          is_goods_show_status: true
        });
        WxParse.wxParse('g_description', 'html', xyz_data.data.goods_info.g_description, _this, 5);
      }
    });
  },
  close_goods_show_status: function () {
    let _this = this;
    _this.setData({
      this_goods_show_info: '',
      is_goods_show_status: false
    });
  },
  /**打开选择规格弹窗*/
  guige_select_bind: function (e) {
    let _this = this;
    let goods_id = e.currentTarget.id || 0;
    wx.showLoading({
      title: '加载中'
    })
    let requestData = {};
    requestData.goods_id = goods_id;
    _requsetCYZ.cyz_requestPost('/CantingIndex/goodsInfo', requestData, function (xyz_data) {
      wx.hideToast();
      if (xyz_data.code == 2) {
        app.getUserDataToken(function (token) {
          _this.guige_select_bind(e);
        });
        return false;
      } else if (xyz_data.code == 1) {
        _this.setData({
          this_goods_show_info: xyz_data.data.goods_info,
          this_spec_attr: xyz_data.data.goods_info.spec_attr,
          this_spec_list: xyz_data.data.goods_info.spec_list,
          guigeIsShow: true
        });

        let this_spec_attr = _this.data.this_spec_attr;
        goodsSpecArr = [];
        for (let i in this_spec_attr) {
          for (let j in this_spec_attr[i].spec_items) {
            if (j < 1) {
              this_spec_attr[i].spec_items[0].checked = true;
              goodsSpecArr[i] = this_spec_attr[i].spec_items[0].item_id;
            }
          }
        }
        _this.setData({
          this_spec_attr: this_spec_attr
        });
        _this._updateSpecGoods();
      }
      wx.hideLoading();
    });
  },

  /**关闭规格弹窗*/
  attr_select_clost_bind: function () {
    this.setData({
      guigeIsShow: false,
      goods_attr_select: {},
      this_g_cate_key: null,
      this_g_good_key: null
    });
  },
  /**
   * 选择规格
   */
  select_attr_bind: function (e) {
    let _this = this,
        attrIdx = e.currentTarget.dataset.attrIdx,
        itemIdx = e.currentTarget.dataset.itemIdx,
        spec_attr = _this.data.this_spec_attr;
    for (let i in spec_attr) {
      for (let j in spec_attr[i].spec_items) {
        if (attrIdx == i) {
          spec_attr[i].spec_items[j].checked = false;
          if (itemIdx == j) {
            spec_attr[i].spec_items[itemIdx].checked = true;
            goodsSpecArr[i] = spec_attr[i].spec_items[itemIdx].item_id;
          }
        }
      }
    }
    _this.setData({
      this_spec_attr: spec_attr
    });
    // 更新商品规格信息
    _this._updateSpecGoods();
  },
  /**
   * 更新商品规格信息
   */
  _updateSpecGoods: function () {
    let _this = this,
        specSkuId = goodsSpecArr.join('_');
    // 查找skuItem
    let spec_list = _this.data.this_spec_list,
        skuItem = spec_list.find((val) => {
          return val.spec_sku_id == specSkuId;
        });
    // 记录goods_sku_id
    // 更新商品价格、划线价、库存
    if (typeof skuItem === 'object') {
      _this.setData({
        this_goods_item_id: _this.data.this_goods_show_info.id + '_' + skuItem.spec_sku_id,
        this_s_sku_id: skuItem.spec_sku_id,
        this_s_shop_price: skuItem.form.sales_price,
        this_s_market_price: skuItem.form.original_price,
        this_s_stock_num: skuItem.form.stock_num,
        this_s_skuCoverImage: skuItem.form.image_url != '' ? skuItem.form.image_url : _this.data.this_goods_show_info.g_img
      });
    }
  },
  //添加购物车
  bind_cart_number_jia: function (e) {
    let _this = this;
    let ckey = e.currentTarget.dataset.ckey;
    let gkey = e.currentTarget.dataset.gkey;
    let key_str = '';
    let cart_data = {};
    //当前购物车的数据
    let base_card_data = wx.getStorageSync(cart_storage_key) || {};

    if (ckey != undefined && gkey != undefined) {
      let this_goods_info = _this.data.this_cate_list[ckey].goods_list[gkey];
      key_str = this_goods_info.id + '_id';
      cart_data = base_card_data[key_str] || {};
      if (Object.keys(cart_data).length > 0) {
        cart_data = {
          'goods_id': this_goods_info.id,
          'goods_name': this_goods_info.g_name,
          'cate_id': this_goods_info.cate_id,
          'cart_goods_number': parseInt(base_card_data[key_str].cart_goods_number) + 1,
          'goods_price': _this.returnFloat(this_goods_info.sku.sales_price),
          'goods_sku_id': '',
          'goods_attr': ''
        };
      } else {
        cart_data = {
          'goods_id': this_goods_info.id,
          'goods_name': this_goods_info.g_name,
          'cate_id': this_goods_info.cate_id,
          'cart_goods_number': 1,
          'goods_price': _this.returnFloat(this_goods_info.sku.sales_price),
          'goods_sku_id': '',
          'goods_attr': ''
        };
      }
    } else {
      let this_goods_info = _this.data.this_goods_show_info;
      key_str = this_goods_info.id + '_' + _this.data.this_s_sku_id;
      cart_data = base_card_data[key_str] || {};

      if (Object.keys(cart_data).length > 0) {
        cart_data = {
          'goods_id': this_goods_info.id,
          'goods_name': this_goods_info.g_name,
          'cate_id': this_goods_info.cate_id,
          'cart_goods_number': parseInt(base_card_data[key_str].cart_goods_number) + 1,
          'goods_price': _this.returnFloat(_this.data.this_s_shop_price),
          'goods_sku_id': _this.data.this_s_sku_id,
          'goods_attr': _this.getAttrBySkuid(_this.data.this_s_sku_id)
        };
      } else {
        cart_data = {
          'goods_id': this_goods_info.id,
          'goods_name': this_goods_info.g_name,
          'cate_id': this_goods_info.cate_id,
          'cart_goods_number': 1,
          'goods_price': _this.returnFloat(_this.data.this_s_shop_price),
          'goods_sku_id': _this.data.this_s_sku_id,
          'goods_attr': _this.getAttrBySkuid(_this.data.this_s_sku_id)
        };
      }
    }

    base_card_data[key_str] = cart_data;
    _this.get_new_card_data(base_card_data);
    wx.setStorageSync(cart_storage_key, base_card_data);

    _this.syn_goods_number();
  },
  //减少购物车
  bind_cart_number_jian: function (e) {
    let _this = this;
    let ckey = e.currentTarget.dataset.ckey;
    let gkey = e.currentTarget.dataset.gkey;
    let key_str = '';
    let cart_data = {};
    //当前购物车的数据
    let base_card_data = wx.getStorageSync(cart_storage_key) || {};
    if (ckey != undefined && gkey != undefined) {
      let this_goods_info = _this.data.this_cate_list[ckey].goods_list[gkey];
      key_str = this_goods_info.id + '_id';
      cart_data = base_card_data[key_str] || {};
      if (Object.keys(cart_data).length > 1) {
        cart_data = {
          'goods_id': this_goods_info.id,
          'goods_name': this_goods_info.g_name,
          'cate_id': this_goods_info.cate_id,
          'cart_goods_number': parseInt(base_card_data[key_str].cart_goods_number) > 1 ? parseInt(base_card_data[key_str].cart_goods_number) - 1 : 0,
          'goods_price': _this.returnFloat(this_goods_info.sku.sales_price),
          'goods_sku_id': '',
          'goods_attr': ''
        };
        base_card_data[key_str] = cart_data;
      } else {
        delete base_card_data[key_str];
      }
    } else {
      let this_goods_info = _this.data.this_goods_show_info;
      key_str = this_goods_info.id + '_' + _this.data.this_s_sku_id;
      //当前购物车的数据
      cart_data = base_card_data[key_str] || {};

      if (Object.keys(cart_data).length > 1) {
        cart_data = {
          'goods_id': this_goods_info.id,
          'goods_name': this_goods_info.g_name,
          'cate_id': this_goods_info.cate_id,
          'cart_goods_number': parseInt(base_card_data[key_str].cart_goods_number) > 1 ? parseInt(base_card_data[key_str].cart_goods_number) - 1 : 0,
          'goods_price': _this.returnFloat(_this.data.this_s_shop_price),
          'goods_sku_id': _this.data.this_s_sku_id,
          'goods_attr': _this.getAttrBySkuid(_this.data.this_s_sku_id)
        };
        base_card_data[key_str] = cart_data;
      } else {
        delete base_card_data[key_str];
      }
    }
    _this.get_new_card_data(base_card_data);
    wx.setStorageSync(cart_storage_key, base_card_data);
    _this.syn_goods_number();
  },
  bind_cart_number_jia_one: function (e) {
    let _this = this;
    let base_card_data = wx.getStorageSync(cart_storage_key) || {};
    base_card_data[e.currentTarget.id].cart_goods_number = parseInt(base_card_data[e.currentTarget.id].cart_goods_number) + 1;
    _this.get_new_card_data(base_card_data);
    wx.setStorageSync(cart_storage_key, base_card_data);
    _this.syn_goods_number();
  },
  bind_cart_number_jian_one: function (e) {
    let _this = this;
    let base_card_data = wx.getStorageSync(cart_storage_key) || {};
    if (base_card_data[e.currentTarget.id].cart_goods_number <= 1) {
      delete base_card_data[e.currentTarget.id];
    } else {
      base_card_data[e.currentTarget.id].cart_goods_number = parseInt(base_card_data[e.currentTarget.id].cart_goods_number) - 1;
    }
    _this.get_new_card_data(base_card_data);
    wx.setStorageSync(cart_storage_key, base_card_data);
    _this.syn_goods_number();
  },
  //获取商品属性文本
  getAttrBySkuid: function (sku_id) {
    let _this = this;
    let spec_attr = _this.data.this_spec_attr;
    let arr = sku_id.split('_');
    let attr_str = '';
    for (let i in spec_attr) {
      for (let j in spec_attr[i].spec_items) {
        for (let q in arr) {
          if (arr[q] == spec_attr[i].spec_items[j].item_id) {
            attr_str += spec_attr[i].group_name + '：' + spec_attr[i].spec_items[j].spec_value + ' ';
          }
        }
      }
    }
    return attr_str;
  },
  //获取最新购物车数据
  get_new_card_data: function (cdata) {
    var that = this;
    var c_all_g_number = 0;
    var c_all_g_price = 0;
    var c_all_g_yunfei = 0;
    var c_goods_count = 0;
    delete cdata.nv_toString;
    var cdata_key_arr = Object.keys(cdata);
    if (cdata_key_arr.length > 0) {
      for (let i = 0; i < cdata_key_arr.length; i++) {
        if(cdata[cdata_key_arr[i]].cart_goods_number > 0){
          c_goods_count = cdata[cdata_key_arr[i]].cart_goods_number;
          c_all_g_number += cdata[cdata_key_arr[i]].cart_goods_number;
          c_all_g_price += c_goods_count * cdata[cdata_key_arr[i]].goods_price;
          cdata[cdata_key_arr[i]].goods_price = that.returnFloat(cdata[cdata_key_arr[i]].goods_price);
        }else{
          delete cdata[cdata_key_arr[i]];
        }
      }
    }
    let all_g_price = that.returnFloat(c_all_g_price);

    that.setData({
      cart_list: cdata,
      all_g_number: c_all_g_number,
      all_g_price: all_g_price,
      all_g_yunfei: 0,
      manjian_yunfei: 0
    });
    if (c_all_g_number == 0) {
      that.setData({
        cart_list_isshow: false
      });
    }
  },
  returnFloat: function (value) {
    if (value <= 0) return '0.00';
    value = Math.round(parseFloat(value) * 100) / 100;
    return value.toFixed(2);
  },
  //显示购物车
  cart_list_show_bind: function () {
    this.setData({
      isShowCartList: !this.data.isShowCartList
    })
  },
  //清空购物车
  cart_delete_bind: function () {
    let that = this;
    wx.showModal({
      title: '提示',
      content: "确认要清空购物车吗",
      confirmText: "确定",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm == true) {
          wx.setStorageSync(cart_storage_key, {})
          let base_card_data = {};
          that.get_new_card_data(base_card_data);
          that.syn_goods_number();
          that.cart_list_show_bind();
        }
      }
    });
  },
  goods_order_bind:function(){
    let _this = this;
    //是否已授权
    if(_this.data.this_user_info.user_auth_status != 2){
      wx.navigateTo({
        url: '/pages/user/authorize/index',
      });
      return false;
    }
    if(_this.data.isSumbitLoading){
      return false;
    }
    if(_this.data.all_g_number <= 0){
      _functionCYZ.CYZ_alert('请选择商品再下单哦');
      return false;
    }
    //验证是否满足配送金额
    if(parseFloat(_this.data.this_canting_setting.canting_waimai_limit_amount) > 0 && _this.data.this_peisong_type == 1){
      if(parseFloat(_this.data.all_g_price) < parseFloat(_this.data.this_canting_setting.canting_waimai_limit_amount)){
        _functionCYZ.CYZ_alert('起送金额为'+_this.data.this_canting_setting.canting_waimai_limit_amount+'元');
        return false;
      }
    }

    let cart_data = wx.getStorageSync(cart_storage_key);
    wx.navigateTo({
      url:"/pages/canting/order?table_id=" + _this.data.this_table_id + "&fendian_id=" + _this.data.this_fendian_id + "&peisong_type="+_this.data.this_peisong_type
    })
  },
  onShareAppMessage: function () {
    var that = this;
    var shareTitle = that.data.this_data_share_title;
    var sharePath = 'pages/canting/index?' + app.getShareUrlParams();
    return {
      title: shareTitle,
      path: sharePath,
      imageUrl: that.data.this_data_share_img
    }
  }
})
